package com.qqt.csr.ixport.task;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.URLUtil;
import cn.idev.excel.FastExcel;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import cn.idev.excel.exception.ExcelDataConvertException;
import com.qqt.csr.common.exception.BizException;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.utils.HttpClientUtil;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.common.utils.SnowflakeUtil;
import com.qqt.csr.ixport.entity.BatchImportTask;
import com.qqt.csr.ixport.entity.ImportTopicConfig;
import com.qqt.csr.ixport.model.ChunkMessage;
import com.qqt.csr.ixport.service.BatchImportTaskService;
import com.qqt.csr.ixport.service.FileChunkProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: yang hao
 * @Date: 2025/2/6 14:58
 * @Description: 任务处理器
 **/
@Slf4j
public class TaskProcessor implements Runnable {
    private static final String TMP_FILE_PATH = "tmp/import/";

    /**
     * 任务
     */
    private final BatchImportTask task;

    /**
     * 推送分片到topic的配置
     */
    private final ImportTopicConfig topicConfig;

    /**
     * 任务服务
     */
    private final BatchImportTaskService batchImportTaskService;

    /**
     * 文件分片生产者 MQ
     */
    private final FileChunkProducer fileChunkProducer;

    /**
     * 构造器
     *
     * @param task                   任务
     * @param batchImportTaskService 任务服务
     * @param fileChunkProducer      文件分片生产者 MQ
     */
    public TaskProcessor(BatchImportTask task, BatchImportTaskService batchImportTaskService,
                         FileChunkProducer fileChunkProducer, ImportTopicConfig topicConfig) {
        this.task = task;
        this.batchImportTaskService = batchImportTaskService;
        this.fileChunkProducer = fileChunkProducer;
        this.topicConfig = topicConfig;
    }

    /**
     * Runs this operation.
     */
    @Override
    public void run() {
        Path dataFilePath = null;
        try {
            if (StringUtils.isBlank(task.getDataSourceDownUrl())) {
                handleFailure("下载文件地址为空");
                return;
            }
            if (topicConfig == null || StringUtils.isBlank(topicConfig.getTopic())) {
                handleFailure("推送分片数据的topic为空");
                return;
            }
            // 更新任务状态为运行中
            if (isInterruptTask(task) || !batchImportTaskService.updateTaskRunning(task)) {
                return;
            }
            // 下载文件到临时目录
            dataFilePath = downLoadDataFile();
            // 解析文件
            parseDataFile(dataFilePath, task);
        } catch (Exception e) {
            log.error("导入任务处理异常,taskId:{}", task.getId(), e);
            handleFailure("处理文件报错，" + e.getMessage());
        } finally {
            // 删除文件
            deleteDataFile(dataFilePath);
        }
    }

    /**
     * 下载文件到临时目录
     *
     * @return
     * @throws Exception
     */
    private Path downLoadDataFile() throws Exception {
        String path = URLUtil.getPath(task.getDataSourceDownUrl());
        String fileDir = TMP_FILE_PATH + path.substring(0, path.lastIndexOf(StrPool.SLASH));

        Path fileDirPath = Paths.get(fileDir);
        if (!Files.exists(fileDirPath)) {
            Files.createDirectories(fileDirPath);
        }

        String fileName = path.substring(path.lastIndexOf(StrPool.SLASH) + 1);
        String prefix = fileName.substring(0, fileName.lastIndexOf(StrPool.DOT));
        String suffix = fileName.substring(fileName.lastIndexOf(StrPool.DOT));
        Path tempFile = Files.createTempFile(fileDirPath, prefix, suffix);

        HttpClientUtil.downLoadFile(task.getDataSourceDownUrl(), inputStream -> {
            try (ReadableByteChannel inChannel = Channels.newChannel(inputStream);
                 FileChannel outChannel = FileChannel.open(tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
                outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE);
            } catch (IOException e) {
                log.error("文件下载失败：taskId:{},downUrl:{}", task.getId(), task.getDataSourceDownUrl(), e);
                throw new BizException("文件下载失败");
            }
        });
        return tempFile;
    }

    /**
     * 解析数据文件，并生成文件分片
     *
     * @param dataFilePath
     * @param task
     */
    private void parseDataFile(Path dataFilePath, BatchImportTask task) {
        if (isInterruptTask(task)) {
            return;
        }
        FastExcel.read(dataFilePath.toFile(), new AnalysisEventListener<Map<Integer, String>>() {
            private static final int BATCH_COUNT = 300;
            private final List<Map<String, String>> cachedDataList = new ArrayList<>(BATCH_COUNT);
            private final AtomicInteger chunkIndex = new AtomicInteger(0);
            private int realRowCount = 0;

            @Override
            public void invoke(Map<Integer, String> rowDataMap, AnalysisContext analysisContext) {
                Map<String, String> copyRowDataMap = new HashMap<>();
                rowDataMap.forEach((index, v) -> {
                    copyRowDataMap.put(index.toString(), v);
                });
                cachedDataList.add(copyRowDataMap);
                realRowCount++;
                if (cachedDataList.size() >= BATCH_COUNT) {
                    processRowData(analysisContext, task, false);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                if (CollectionUtils.isNotEmpty(cachedDataList)) {
                    processRowData(analysisContext, task, true);
                }
            }

            private void processRowData(AnalysisContext analysisContext, BatchImportTask task, boolean isAll) {
                if (isInterruptTask(task)) {
                    throw new BizException(StatusCode.Common.INTERRUPT_TASK, "任务被中断，taskId：" + task.getId());
                }

                int index = chunkIndex.getAndIncrement();
                if (task.getSuccessCount() >= realRowCount) {
                    // 暂停后重新开始的话，需要跳过已经处理的
                    cachedDataList.clear();
                    return;
                }

                boolean isSuccess = sendChunk(index, cachedDataList);
                cachedDataList.clear();
                ServiceAssert.isTrue(isSuccess, StatusCode.Common.MQ_EXCEPTION.getCode(), "发送文件分片失败");

                task.setSuccessCount(realRowCount);
                if (isAll) {
                    task.setDataTotal(realRowCount);
                    batchImportTaskService.updateTaskSuccess(task);
                } else {
                    Integer totalRowNumber = analysisContext.readSheetHolder().getApproximateTotalRowNumber();
                    task.setDataTotal(totalRowNumber);
                    batchImportTaskService.updateTaskCount(task);
                }
            }

            @Override
            public void onException(Exception exception, AnalysisContext context) {
                log.error("解析失败，taskId:{}，异常信息: {}", task.getId(), exception.getMessage());
                cachedDataList.clear();
                if (exception instanceof ExcelDataConvertException ex) {
                    log.error("taskId:{}，第 {} 行, 第 {} 列解析异常, 数据: {}", task.getId(), ex.getRowIndex(), ex.getColumnIndex(), ex.getCellData());
                } else if (exception instanceof BizException ex) {
                    if (StatusCode.Common.INTERRUPT_TASK.equals(ex.getStatusCode())) {
                        return;
                    }
                }
                handleFailure(exception.getMessage());
            }
        }).charset(StandardCharsets.UTF_8).sheet().doRead();
    }

    /**
     * 发送分片
     *
     * @param index       分片下标
     * @param rowDataList 数据
     */
    private boolean sendChunk(int index, List<Map<String, String>> rowDataList) {
        ChunkMessage chunk = new ChunkMessage();
        chunk.setSeqId(SnowflakeUtil.nextIdStr());
        chunk.setTaskId(task.getId());
        chunk.setTenantId(task.getTenantId());
        chunk.setCreatorId(task.getCreatorId());
        chunk.setChunkIndex(index);
        chunk.setRowDataList(rowDataList);

        task.setRetryTimes(0);
        while (task.getRetryTimes() < task.getRetryTimesCfg()) {
            if (isInterruptTask(task)) {
                throw new BizException(StatusCode.Common.INTERRUPT_TASK, "任务被中断，taskId：" + task.getId());
            }
            try {
                if (fileChunkProducer.sendChunk(topicConfig, chunk)) {
                    return true;
                }
            } catch (Exception e) {
                log.error("【send file chunk】error,taskId:{},index:{},retryTimes:{}", task.getId(), index, task.getRetryTimes(), e);
            }
            task.setRetryTimes(task.getRetryTimes() + 1);
        }
        return false;
    }

    /**
     * 处理失败
     *
     * @param reason 失败原因
     */
    private void handleFailure(String reason) {
        task.setFailReason(StringUtils.substring(reason, 0, 2000));
        batchImportTaskService.updateTaskFail(task);
    }

    /**
     * 是否中断任务
     *
     * @param task
     * @return
     */
    private boolean isInterruptTask(BatchImportTask task) {
        return batchImportTaskService.isInterruptTask(task.getId());
    }

    private void deleteDataFile(Path dataFilePath) {
        if (dataFilePath == null) {
            return;
        }
        try {
            Files.deleteIfExists(dataFilePath);
        } catch (IOException e) {
            log.error("删除临时文件失败：taskId:{},tempFile:{}", task.getId(), dataFilePath, e);
        }
    }
}
